package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.config.R;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
//    该类专门用于匹配请求路径
    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpServletRequest request =(HttpServletRequest)servletRequest;
//        获取本次求请的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        //3. 定义一个数组存储需要放行的url，判断本次请求是否需要登录权限的。
        String[]urls={"/backend/**","/front/**","/employee/login","/common/**","/user/sendMsg","/user/login","/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};
//        4.进行路径匹配，匹配成功放行
            boolean flag=checkUrl(urls,requestURI);
            if (flag){
                log.info("本次请求{}不需要处理",requestURI);
                filterChain.doFilter(request,response);
                return;
            }
//            6.判断是否登录,登录放行
            HttpSession session=request.getSession();
            Object employee = session.getAttribute("employee");
            if (employee!=null){
                log.info("用户已登录");
                filterChain.doFilter(request,response);
                return;
            }
        Object userId = session.getAttribute("user");
        if (userId!=null){
            log.info("用户已登录");
            filterChain.doFilter(request,response);
            return;
        }

//          如果没有登录，跳转回登录页面
        log.info("用户未登录");
        String topage = JSON.toJSONString(R.error("NOTLOGIN"));
            response.getWriter().write(topage);
    }


/*
    匹配url的放法
 */
    private boolean checkUrl(String[] urls, String requestURI) {
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)){
            return true;
            }
        }
        return false;
    }
}
